#include "app_message.h"


/**
 * @brief 把json转换为字节数组
 */

//{"device_id":1,"target_angle":3600,"max_speed",60} ==> 01 00 00 xx xx 00 00  xx xx 
 int app_message_jsonToChars(  char *json, char *buffer, int buffer_len)
{
     if(buffer_len<9)
     {
        log_error("buffer is too small ");
     }
     cJSON *root = cJSON_Parse(json);
     if(root==NULL)
     {
        perror("json is invalid ");
         
     }

     cJSON *device_id_cjson=  cJSON_GetObjectItem(root, "device_id");
     cJSON *target_angle_cjson=  cJSON_GetObjectItem(root, "target_angle");
     cJSON *max_speed_cjson=  cJSON_GetObjectItem(root, "max_speed");

     int device_id=  device_id_cjson->valueint ;
     float target_angle= (float) target_angle_cjson->valuedouble ;
     float max_speed= (float) max_speed_cjson->valuedouble ;

     buffer[0]=device_id;
     memcpy(buffer+1, &target_angle, 4);
     memcpy(buffer+5, &max_speed, 4);

     
     app_common_printHex("app_message_jsonToChars :", buffer, 9);
     cJSON_Delete(root);
     return 9;


}
 

/**
 * @brief 把字节数组转换为json
 */
char   *app_message_charsToJson(  char *data, int data_len   )
{
      // 先把data提取成值
      uint8_t device_id=data[0];
      float cur_angle= 0;
      bool  motor_status=data[6];
      
      // 把值写入cjson结构体
      memcpy(&cur_angle, data+1, 4);
 
      // cjson结构体 生成json字符串
      cJSON *root = cJSON_CreateObject();
      cJSON_AddNumberToObject(root, "device_id", device_id);
      char cur_angle_chr[7];
      sprintf(cur_angle_chr, "%6.1f", cur_angle);
      cJSON_AddStringToObject(root, "cur_angle", cur_angle_chr);
      cJSON_AddStringToObject(root, "motor_status", motor_status?"on":"off");

      char *jsonstr=   cJSON_PrintUnformatted(root );
       cJSON_Delete(root);
      return jsonstr;
      
}